package com.collegeproject.weatherapp.fragments;

import java.util.HashMap;

import org.apache.http.entity.StringEntity;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.collegeproject.weatherapp.R;
import com.collegeproject.weatherapp.StartActivity.FragmentListener;
import com.collegeproject.weatherapp.library.AsyncResponse;
import com.collegeproject.weatherapp.library.ConnectionDetector;
import com.collegeproject.weatherapp.library.DatabaseHandler;
import com.collegeproject.weatherapp.library.HTTPfunctions;

public class PostFragment extends Fragment implements AsyncResponse {
	Button btnPost, btnBack;
	TextView error;
	static FragmentListener _listener;
	
	ConnectionDetector cd;
	
	private String mMessage, mLocation;
	EditText inputLocation, inputMessage;

	private static final String TAG = "PostFragment";
	private static final String POSTAUTH = "POSTAUTH";
	private static String postURL = "http://x00068868.cloudapp.net/WeatherAppService/rest/post";

	// private static String localpostURL =
	// "http://10.0.2.2:8080/WeatherAppService.svc/rest/post";

	public static PostFragment newInstance(FragmentListener listener) {
		PostFragment f = new PostFragment();
		_listener = listener;
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initViews();
		cd = new ConnectionDetector(getActivity());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.post, container, false);
	}

	@Override
	public void onStart() {

		inputMessage.setOnEditorActionListener(new OnEditorActionListener() {

			@SuppressWarnings("static-access")
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {

				if (actionId == EditorInfo.IME_ACTION_SEND) {

					mMessage = inputMessage.getText().toString().trim();
					mLocation = inputLocation.getText().toString().trim();

					// try to post message to server
					attemptPost(mMessage, mLocation);

					// hide the keyboard
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									getActivity().INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

					return true;
				}
				return false;
			}
		});

		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// switch to dash board fragment
				_listener.onSwitchToNextFragment();
			}
		});

		// try to post message to server
		btnPost.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mMessage = inputMessage.getText().toString().trim();
				mLocation = inputLocation.getText().toString().trim();

				// try to post message to server
				attemptPost(mMessage, mLocation);
			}
		});
		super.onStart();
	}

	private void attemptPost(String mMessage, String mLocation) {
		inputLocation.setError(null);
		inputMessage.setError(null);

		boolean cancel = false;
		View focusView = null;

		// checking for valid location
		if (TextUtils.isEmpty(mLocation)) {
			inputLocation.setError(getString(R.string.error_field_required));
			focusView = inputLocation;
			cancel = true;
		}

		// checking for valid message
		if (mMessage.length() < 5) {
			inputMessage.setError(getString(R.string.error_field_lesschar));
			focusView = inputMessage;
			cancel = true;
		}

		if (cancel) {
			focusView.requestFocus();
		} else {
			try {
				Boolean connected = cd.isConnectingToInternet();
				if (connected){
					// get user details to be sent with post for validation
					DatabaseHandler db = new DatabaseHandler(getActivity());
					HashMap<String, String> user = new HashMap<String, String>(
							db.getUserDetails());

					String source = user.get("username") + ":"
							+ user.get("password");
					String base64 = Base64.encodeToString(
							source.getBytes("UTF-8"), Base64.URL_SAFE
									| Base64.NO_WRAP);

					JSONObject postToPost = new JSONObject();
					postToPost.put("PostLocation", mLocation);
					postToPost.put("PostMessage", mMessage);

					StringEntity se = new StringEntity(postToPost.toString());
					HTTPfunctions task = new HTTPfunctions(getActivity(),
							POSTAUTH, se, base64);
					task.listener = this;
					task.execute(new String[] { postURL });
				} else {
					error.setText("No internet connection available");
					error.setVisibility(View.VISIBLE);
				}
			} catch (Exception ex) {
				Log.e(TAG, " Attempt Post " + ex.getMessage());
			}
		}
	}

	@Override
	public void processFinish(String result) {
		try {
			JSONObject jsonObject = new JSONObject(result);
			int success = Integer.parseInt(jsonObject.getString("Success"));
			if (success == 0) { // successful

				// if success show toast/confirmation to user
				Toast.makeText(getActivity(), "Messaged successfully posted!",
						Toast.LENGTH_LONG).show();

				// switch to dash board fragment
				_listener.onSwitchToNextFragment();
			} else if (success == 3) {
				error.setText(jsonObject.getString("ErrorMessage")); // error
				error.setVisibility(View.VISIBLE);
			} else {
				error.setText(jsonObject.getString("ErrorMessage"));// error
				error.setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			Log.e(TAG, "Post Result " + e.getMessage());
		}
	}

	private void initViews() {
		inputLocation = (EditText) getView().findViewById(
				R.id.edit_post_location);
		inputMessage = (EditText) getView()
				.findViewById(R.id.edit_post_message);
		error = (TextView) getView().findViewById(R.id.post_error);
		btnPost = (Button) getView().findViewById(R.id.button_post);
		btnBack = (Button) getView().findViewById(R.id.button_post_back);
	}	
}